package com.wpf.system.common.utils.excelListener;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.wpf.system.entity.Equipment;
import com.wpf.system.service.EquipmentService;

import java.util.ArrayList;
import java.util.List;

public class EquipmentExcelListener extends AnalysisEventListener<Equipment>{
    private EquipmentService equipmentService;

    private List<Equipment> list = new ArrayList<>();
    //每20条存储一次
    private static final int batchCount = 20;
    private int count = 0;

    public int getCount() {
        return count;
    }

    public EquipmentExcelListener(EquipmentService equipmentService) {this.equipmentService = equipmentService;}

    @Override
    public void invoke(Equipment equipment, AnalysisContext analysisContext) {
        list.add(equipment);
        count++;
        if (list.size() >= batchCount) {
            saveEquipment();
            // 存储完成清理 list
            list = ListUtils.newArrayListWithExpectedSize(batchCount);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveEquipment();
    }

    public void saveEquipment(){
        for( Equipment equipment : list ){
            equipment.setEquipmentNo(IdUtil.objectId());
            equipmentService.save(equipment);
        }
    }
}
